package cn.codeforfun.exchage;

import cn.codeforfun.consts.SessionConsts;
import cn.codeforfun.follower.Follower;
import cn.codeforfun.follower.FollowerService;
import cn.codeforfun.prize.Prize;
import cn.codeforfun.prize.PrizeService;
import cn.codeforfun.utils.RandomUtil;
import cn.codeforfun.vote.Vote;
import cn.codeforfun.vote.VoteService;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.*;

/**
 * Created by Administrator on 2017/2/18 0018.
 */
@Service
@Transactional
public class ExchangeService {
    @Autowired
    private ExchangeDao exchangeDao;
    @Autowired
    private VoteService voteService;
    @Autowired
    private FollowerService followerService;
    @Autowired
    private PrizeService prizeService;


    public Map getCode(Integer code) {
        List<Exchange> exchangeList = exchangeDao.findByCode(code);
        if (CollectionUtils.isEmpty(exchangeList)) return null;
        for (Exchange exchange : exchangeList) {
            Prize prize = prizeService.findOne(exchange.getPrizeId());
            if (prize == null) return null;
            exchange.setPrize(prize);
            Follower follower = followerService.findOne(exchange.getFollowerId());
            exchange.setFollowerId(follower.getId());
            exchange.setFollower(follower);
        }

        Map map = new HashMap();
        map.put("exchangeList", exchangeList);
        return map;
    }

    public void hasExchange(String voteId, String followerId) {
        if (voteId == null || followerId == null) return;
        Long fId = Long.valueOf(followerId);
        Long vId = Long.valueOf(voteId);
        Exchange one = exchangeDao.findByFollowerIdAndVoteId(fId, vId);
        one.setHasGet(true);
        exchangeDao.save(one);
    }

    public List<Exchange> findWithFollowerAndPrize() {
        List<Exchange> exchanges = exchangeDao.findWithFollowerAndPrize();
        return exchanges;
    }

    public Map showPrice(HttpSession session) throws WxErrorException {
        Long voteId = Long.valueOf(String.valueOf(session.getAttribute(SessionConsts.VOTE_ID)));
        String openId = (String) session.getAttribute(SessionConsts.OPEN_ID);
        Follower follower = followerService.sysncFollower(openId);
        Exchange exchange = exchangeDao.findByFollowerIdAndVoteId(follower.getId(), voteId);
        Long prizeId = exchange.getPrizeId();
        if (exchange.getHasPrize()) {
            Map map = new HashMap();
            Prize prize = prizeService.findOne(prizeId);
            map.put("prize", prize);
            map.put("code", exchange.getCode());
            map.put("hasExchange", exchange.getHasGet());
            return map;
        }
        return null;
    }
}
